package com.konsung.ksdc.config;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;

import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.crash.CrashHandler;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.widget.ReLoginPopupWindow;
import com.konsung.ksdc.manager.appmain.LoginActivity;
import com.konsung.ksdc.manager.appmain.MainActivity;
import com.konsung.ksdc.service.MqttService;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/3/8 0008.
 */
public class MyApplication extends Application {
    private static Context mContext;
    public static Activity mCurrentActivity; // 获取当前的activity对象

    // 重新登录弹窗
    private ReLoginPopupWindow reloginPopupWindow;

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
            }

            @Override
            public void onActivityResumed(Activity activity) {
                mCurrentActivity = activity;

                if (activity instanceof MainActivity) {
                    checkReLogin();
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                if (activity instanceof MainActivity) {
                    stopMqttService();
                }
            }
        });

        mContext = getApplicationContext();
        //是否抓取奔溃日志，初始化奔溃日志工具
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(),
                    PackageManager.GET_META_DATA);
            boolean isCatch = appInfo.metaData.getBoolean("catch");
            if (isCatch) {
                //正式测试,储存本地
                CrashHandler.getInstance().init(mContext);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        generateDeviceCode();
        initReloginPopupWindow();
        registerBroadcast();
    }

    /**
     * 停止MQTT服务
     */
    private void stopMqttService() {
        Intent intent = new Intent(this, MqttService.class);
        stopService(intent);
    }

    /**
     * 启动MQTT服务
     */
    private void startMqttService() {
        Intent intent = new Intent(this, MqttService.class);
        startService(intent);
    }

    /**
     * 注册广播
     */
    private void registerBroadcast() {
        IntentFilter intent = new IntentFilter();
        intent.addAction(BroadCastActions.ACTION_RE_LOGIN);
        registerReceiver(receiver, intent);
    }

    /**
     * 广播接受者
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (BroadCastActions.ACTION_RE_LOGIN.equals(intent.getAction())) {
                checkReLogin();
            }
        }
    };

    /**
     * 初始化重新登录弹窗
     */
    private void initReloginPopupWindow() {
        reloginPopupWindow = new ReLoginPopupWindow(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reloginPopupWindow.dismiss();

                // 清空Activity栈，回到登录页面
                Intent intent = new Intent(MyApplication.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                startActivity(intent);
            }
        });
    }

    /**
     * 显示重新登录弹窗
     */
    public void checkReLogin() {
        // 检查网络设置是否有效
        if (!RequestUtils.isNetworkConnected(this)) {
            return;
        }

        // 校验是否被离线顶号
        final String myDeviceCode = PreferenceUtils.getString(this, Constants.DEVICE_CODE);
        RequestUtils.findUserById(NetConfig.currentUser.getUserId(), new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                RegisterUserNetBean user = responseBean.getEntity(RegisterUserNetBean.class);
                String deviceCode = user.getLastLoginIp();
                // 通过设备号，判断是否被顶号，非顶号则重连，顶号则退出到登录页
                if (!myDeviceCode.equals(deviceCode)) {
                    stopMqttService();

                    if (reloginPopupWindow != null && reloginPopupWindow.isShowing()) {
                        return;
                    }
                    // 取消自动登录，即标记自动登录为FALSE
                    PreferenceUtils.putBoolean(MyApplication.this, Constants.AUTO_LOGIN, false);

                    reloginPopupWindow.showAtLocation(MyApplication.mCurrentActivity.getWindow()
                            .getDecorView(), Gravity.CENTER, 0, 0);
                } else {
                    // 如果没有被顶号，则启动MQTT服务
                    startMqttService();
                }
            }
        });
    }

    /**
     * 生成设备唯一码
     */
    private void generateDeviceCode() {
        String deviceCode = PreferenceUtils.getString(this, Constants.DEVICE_CODE);
        if (StringUtils.isEmpty(deviceCode)) {
            PreferenceUtils.putString(this, Constants.DEVICE_CODE, StringUtils.getUuid());
        }
    }

    /**
     * 重新注册
     * @return 控件
     */
    public ReLoginPopupWindow getReloginPopupWindow() {
        return reloginPopupWindow;
    }

    /**
     * @return 上下文
     */
    public static Context getContext() {
        return mContext;
    }

    /**
     * app字体不随系统字体改变而改变
     * @param newConfig 系统属性
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1) {
            //非默认值
            getResources();
        }

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) { //非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults(); //设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }
}
